#!/usr/bin/env python
# -*- coding: gb2312 -*-

# TODO:
#
#
#
"""Test code

Suggested usage: import portscan
"""
__decription__ = "Batch Rename Kit"
__version__    = "0.01"
__date__       = "Mar.18th.2009"
__author__     = "hu <huys03@gmail.com> "
__license__    = "Licensed under the BSD, see the file LICENSE in this tarball."
__copyright__  = "Copyright (C) 2007 by hu <huys03@gmail.com>."

import socket
import urllib2
from sets import Set
import sys
from time import sleep

class PortScan:
    ###
    def __init__(self, subnet='166.111.36.', port = 8282):
        self.START = 1
        self.END   = 255

        self.host = subnet
        #host = '59.66.124.'

        self.port = port

        self.result = Set()

        ### If not responsing immediately, pass it.
        #print socket.getdefaulttimeout()
        socket.setdefaulttimeout(.4)

    def scan(self):

        for addr in range(self.START, self.END):
            print self.host + str(addr)
            #    continue
            s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

            try:
                s.connect((self.host+str(addr), self.port))
            except socket.error, msg:
                s = None
                print msg
                if msg == "timed out":
                    continue
                else:
                    continue
                #       sys.exit(11)

            try:
                s.send('Hello, world')
            except socket.error, msg:
                s.close()
                s = None
                sys.exit(22)

            try:
                data = s.recv(1024)
                print 'Received', repr(data)
                if data.startswith("SSH"):
                    result.add(self.host + str(addr))
            except socket.error, msg:
                print 'recv error: ' + str(msg)
            
            s.close()
            """
            PROXY = 'http://' + self.host + str(addr) + ':' + str(self.port)
            proxy_handler = urllib2.ProxyHandler({'http':PROXY})
            opener = urllib2.build_opener(proxy_handler)

            try:
                g = opener.open('http://info.tsinghua.edu.cn/')
                data = g.read()
            #print data
                if None <> data:
                    print 'Proxy is OK'
            except urllib2.HTTPError, e:
                print e
            """


        if 0 <> len(self.result):
            print self.result
        else:
            print "None is the target!"


###
if __name__=="__main__":
    print 'In __main__'
    ps = PortScan()
    ps.scan()
    sleep(5)

